using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerFallingState : PlayerAirborneState
{
    private readonly PlayerFallData fallData;
    private Vector3 playerPosOnEnter;
    public PlayerFallingState(PlayerMovementMachine stateMachine) : base(stateMachine)
    {
        fallData = StateMachine.Player.Data.PlayerAirborneData.FallData;
    }

#region Istate Methods
    public override void Enter()
    {
        base.Enter();
        StateMachine.ReusableData.MovementSpeedModify = 0;
        ResetVerticalVelocity();
        playerPosOnEnter = StateMachine.Player.transform.position;
        StartAnimation(StateMachine.Player.AnimationData.FallParameterHash);        
    }

    public override void PhysicUpdate()
    {
        base.PhysicUpdate();
        LimitVerticalVelocity();
    }

    public override void Exit()
    {
        base.Exit();
        StopAnimation(StateMachine.Player.AnimationData.FallParameterHash);        
    }
#endregion

#region Main Methods
    private void LimitVerticalVelocity()
    {
        Vector3 playerVerticalVelocity = GetVerticalPlayerVelocity();

        if (playerVerticalVelocity.y >= -fallData.FallSpeedLimit)
            return;
        
        Vector3 limitedVerticalVelocity = new Vector3(0, -fallData.FallSpeedLimit - playerVerticalVelocity.y, 0);

        StateMachine.Player.Rigidbody.AddForce(limitedVerticalVelocity, ForceMode.VelocityChange);
    }
#endregion

#region  Reuseable Methods
    protected override void ResetSprintState()
    {
    }

    protected override void OnContactWithGround()
    {
        float fallDistance = Mathf.Abs(playerPosOnEnter.y - StateMachine.Player.transform.position.y);
        if (fallDistance < fallData.MinDistanceToBeConsideredHardFall)
        {
            StateMachine.ChangeState(StateMachine.LightLandingState);
            return;
        }

        if (!StateMachine.ReusableData.ShouldWalk && !StateMachine.ReusableData.ShouldSprint && StateMachine.ReusableData.InputMovement == Vector2.zero)
        {
            StateMachine.ChangeState(StateMachine.HardLandingState);
            return;
        }
        
        StateMachine.ChangeState(StateMachine.RollState);
    }
#endregion
}